package com.yhty.utils;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;

/**
 * 日期处理工具类
 * @author RoySong
 * 2011-3-30-下午05:57:08
 */
public class DateUtil {

	/**
	 * 将sql时间Timestamp类型转换为"yyyy-MM-dd"格式字符串
	 * @param ts
	 * @return
	 */
	public static String getDate(Timestamp ts) {
		if(ts == null)
			return null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date d = new Date(ts.getTime());
		return sdf.format(d);
	}
	
	/**
	 * 将"yyyy-MM-dd"格式字符串转换为int[]{年,月,日}
	 * @param date
	 * @return
	 */
	public static int[] getYearMonthDay(String date){
		int[] result = new int[3];
		try {
			Date d = new Date();
			if(StringUtils.isNotEmpty(date))
				d = DateUtils.parseDate(date, new String[]{"yyyy-MM-dd"});
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(d);
			result[0] = calendar.get(Calendar.YEAR);
			result[1] = calendar.get(Calendar.MONTH)+1;
			result[2] = calendar.get(Calendar.DAY_OF_MONTH);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
		return result;
	}
	
	/**
	 * 获取当前日期字符串，格式：yyyy-MM-dd
	 * @return
	 */
	public static String getToday(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(new Date());
	}
	
	/**
	 * 获取上个月的今天
	 * @return
	 */
	public static String getLastMonthToday(){
		String str = "";   
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");   
		Calendar lastDate = Calendar.getInstance();   
		lastDate.set(Calendar.DATE, 1);// 设为当前月的1号   
		lastDate.add(Calendar.MONTH, -1);// 减一个月，变为下月的1号   
		// lastDate.add(Calendar.DATE,-1);//减去一天，变为当月最后一天   
		str = sdf.format(lastDate.getTime());   
		return str;   
	}

	/**
	 * 判断传入日期是否是本月
	 * @param rDate
	 * @return
	 */
	public static boolean isSameMonth(String rDate) {
		if(StringUtils.isEmpty(rDate))
			return false;
		int[] inDate = getYearMonthDay(rDate);
		int[] now = getYearMonthDay(getToday());
		return inDate[0]==now[0]&&inDate[1]==now[1];
	}
}
